package com.sdhs.common.utils;

/**
 * @author zhangmy
 * @date 2024/5/2310:23
 * @Description: 竹云加密解密工具类
 */

import com.alibaba.fastjson2.JSONObject;
import com.banboocloud.Codec.BamboocloudFacade;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 竹云提供的工具类
 */
@Slf4j
public abstract class BambooCloudUtils {
    public static boolean checkUsernamePassword(String username, String password) {
        log.info("username --->" + username + "  password --- >" + password + " ----ok");
        return "bbcadmin".equals(username) && "P@ssw0rd".equals(password);
    }

    /**
     * 解密请求参数
     *
     * @param ciphertext 加密数据
     * @param key        解密密钥
     * @param type       类型
     * @return 解密后的数据
     */
    public static String getPlaintext(String ciphertext, String key, String type) {
        return BamboocloudFacade.decrypt(ciphertext, key, type);
    }

    public static Boolean verify(Map<String, Object> requestMap, String type) {
        Map<String, Object> verifymap = new TreeMap<>();
        StringBuilder sb = new StringBuilder();
        for (String key : requestMap.keySet()) {
            verifymap.put(key, requestMap.get(key));
        }
        for (String key : verifymap.keySet()) {
            if (!"signature".equals(key)) {
                sb.append(key).append("=").append(verifymap.get(key)).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(requestMap.get("signature") + "  now  " + sb);
        return BamboocloudFacade.verify(requestMap.get("signature").toString(), sb.toString(), type);
    }

    /**
     * HttpServletRequest解密返回Map
     *
     * @param request 请求参数
     * @return 请求参数Map
     */
    public static Map<String, Object> getRequestForMap(HttpServletRequest request) {
        StringBuilder sb = builderRequestString(request);
        if (StringUtils.isBlank(sb.toString())) {
            return new HashMap<>();
        }
        String requestBody = sb.toString();
        log.info("解密前requestBody-->" + requestBody);
        requestBody = getPlaintext(requestBody, "123456", "AES");
        log.info("解密后requestParam-->" + requestBody);
        Map<String, Object> rtnMap = new HashMap<>();
        JSONObject json = JSONObject.parse(requestBody);
        for (String key : json.keySet()) {
            rtnMap.put(key, json.get(key));
        }
        return rtnMap;
    }

    /**
     * HttpServletRequest解密格式化返回Map
     *
     * @param request 请求参数
     * @return 请求参数Map
     */
    public static Map<String, Object> getRequestFormatForMap(HttpServletRequest request) {
        StringBuilder sb = builderRequestString(request);
        if (StringUtils.isBlank(sb.toString())) {
            return new HashMap<>();
        }
        //修改多值的属性格式方便转换
        String requestBody = BambooCloudUtils.getPlaintext(sb.toString(), "123456", "AES");
        String prefix = "[\"";
        String suffix = "\"]";
        String tempData = "";
        while (requestBody.contains(prefix)) {
            tempData = requestBody.substring(requestBody.indexOf(prefix), requestBody.indexOf(suffix) + 2)
                    .replace(prefix, "\"")
                    .replace(suffix, "\"")
                    .replace("\",\"", ",");
            requestBody = requestBody.substring(0, requestBody.indexOf(prefix))
                    + tempData + requestBody.substring(requestBody.indexOf(suffix) + 2);
        }
        log.info("requestBody-->" + requestBody);
        Map<String, Object> rtnMap = new HashMap<>();
        JSONObject json = JSONObject.parse(requestBody);
        for (String key : json.keySet()) {
            rtnMap.put(key, json.get(key));
        }
        return rtnMap;
    }

    public static StringBuilder builderRequestString(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String temp = "";
        try {
            br = request.getReader();
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (br != null)
                try {
                    br.close();
                } catch (IOException eo) {
                    eo.printStackTrace();
                }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }
}
